package lt.marsrutai.mobile.android.listener;

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;


public class BookmarkTabListener<T extends Fragment> implements TabListener {

    private Fragment fragment;
    private final Activity activity;
    private final Class<T> cls;

    public BookmarkTabListener(Activity activity, Class<T> cls) {
        this.activity = activity;
        this.cls = cls;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (fragment == null) {
            // If not, instantiate and add it to the activity
            fragment = Fragment.instantiate(activity, cls.getName());
            ft.add(android.R.id.content, fragment);
        } else {
            // If it exists, simply attach it in order to show it
            ft.attach(fragment);
        }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (fragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(fragment);
        }
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }

}
